package com.hh.service.service.impl.integral;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hh.common.exception.HhException;
import com.hh.common.model.integral.PointsMallGoods;
import com.hh.service.dao.integral.PointsMallGoodsDao;
import com.hh.service.service.integral.PointsMallGoodsService;
import org.springframework.stereotype.Service;

@Service
public class PointsMallGoodsServiceImpl extends ServiceImpl<PointsMallGoodsDao, PointsMallGoods> implements PointsMallGoodsService {
    @Override
    public Boolean operationStock(Integer id, Integer num, String type) {
        UpdateWrapper<PointsMallGoods> updateWrapper = new UpdateWrapper<>();
        if (type.equals("add")) {
            updateWrapper.setSql(StrUtil.format("stock = stock + {}", num));
            updateWrapper.setSql(StrUtil.format("sales = sales - {}", num));
        }
        if (type.equals("sub")) {
            updateWrapper.setSql(StrUtil.format("stock = stock - {}", num));
            updateWrapper.setSql(StrUtil.format("sales = sales + {}", num));
            // 扣减时加乐观锁保证库存不为负
            updateWrapper.last(StrUtil.format(" and (stock - {} >= 0)", num));
        }
        updateWrapper.eq("id", id);
        boolean update = update(updateWrapper);
        if (!update) {
            throw new HhException("更新普通商品库存失败,商品id = " + id);
        }
        return update;
    }
}
